

import 'IState.dart';
import 'ITransition.dart';

abstract class IStateMachine {
  IState? _curState;
  final Map<String, IState> _states = {};

  IState? get curState => _curState;

  /// 最近一次转换动作
  late ITransition _curTransition;

  ITransition get curTransition => _curTransition;

  void addState(IState? state) {
    if(state == null || state.name == null || state.name == "") return;
    _states[state.name!] = state;
    state.setStateMachine(this);
  }

  void removeState(IState? state) {
    if(state == null || state.name == null || state.name == "") return;
    _states.remove(state.name);
  }

  void setCurState(IState? state) {
    if(state == null || state.name == null || state.name == "") return;
    if(!_states.containsKey(state.name)) return;
    state.setStateMachine(this);
    _curState?.onExit(state);
    state.onEnter(_curState);
    _curState = state;
  }

  void setCurTransition(ITransition transition) {
    _curTransition = transition;
  }

  IState getStateWithTag(String tag) {
    return _states.values.firstWhere((item)=> item.tag == tag);
  }

  IState? getStateWithName(String? name) {
    if(name == null || name == "") return null;
    if(!_states.containsKey(name)) return null;
    return _states[name];
  }
  
  void updateState(ITransition transition) {
    if (_curState!=null)
    {
      _curState!.onUpdate(transition);
      transition.onCompleteCallBack();
    }
  }
}